// 搜索结果页面
const { searchNotices } = require('../../../api/notice')
const { searchServiceItems } = require('../../../api/serviceItems')

Page({
  data: {
    query: '',
    results: [],
    loading: false,
    searchInfo: null,
    pagination: null,
    // 全局加载状态
    globalLoading: false,
    globalLoadingText: '页面加载中...'
  },

  // 显示全局加载
  showGlobalLoading(text = '页面加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

  onLoad(options) {
    // 显示页面加载效果
    this.showGlobalLoading('页面加载中...')
    console.log('搜索结果页面加载')
    
    // 从全局数据中获取搜索结果
    const app = getApp()
    const globalData = app.globalData || {}
    const searchResults = globalData.searchResults || []
    const searchQuery = globalData.searchQuery || ''
    const searchInfo = globalData.searchInfo || null
    const pagination = globalData.pagination || null
    
    console.log('搜索结果:', { searchQuery, searchResults, searchInfo, pagination })
    
    // 格式化搜索结果，支持服务事项和公告两种类型
    const formattedResults = this.formatSearchResults(searchResults)
    
    this.setData({
      query: searchQuery,
      results: formattedResults,
      searchInfo: searchInfo,
      pagination: pagination
    })
    
    // 清理全局数据
    if (globalData.searchResults) {
      delete globalData.searchResults
    }
    if (globalData.searchQuery) {
      delete globalData.searchQuery
    }
    if (globalData.searchInfo) {
      delete globalData.searchInfo
    }
    if (globalData.pagination) {
      delete globalData.pagination
    }
    
    // 测试搜索功能（开发调试用）
    if (formattedResults.length === 0) {
      console.log('没有搜索结果，测试搜索功能')
      this.testSearch()
    }
    
    // 页面加载完成，隐藏加载状态
    setTimeout(() => {
      this.hideGlobalLoading()
    }, 500)
  },

  // 点击搜索结果项
  onTapResult(e) {
    const { type, id } = e.currentTarget.dataset
    console.log('点击搜索结果:', { type, id })
    
    // 根据结果类型进行不同的跳转
    switch (type) {
      case 'service':
        this.navigateToService(id)
        break
      case 'notice':
        this.navigateToNotice(id)
        break
      case 'urgent':
        this.navigateToUrgent(id)
        break
      default:
        // 兼容旧数据，默认为公告类型
        this.navigateToNotice(id)
    }
  },

  // 跳转到服务页面
  navigateToService(id) {
    const serviceMap = {
      'i1': '/pages/service/civil-affairs/apply/index',      // 最低生活保障申请
      'i2': '/pages/service/categories/subsidy/temp-aid/index',   // 临时救助申请
      'i3': '/pages/service/categories/subsidy/extreme-support/index', // 特困供养审核
      'i4': '/pages/service/categories/subsidy/disability-subsidy/index', // 残疾人两项补贴
      'i5': '/pages/service/categories/subsidy/pension-subsidy/index', // 养老补贴申请
      'i6': '/pages/service/categories/approval/homestead-approval/index', // 宅基地申请
      'i7': '/pages/service/categories/approval/danger-house-reform/index', // 危房改造申请
      'i8': '/pages/service/categories/approval/construction-record/index', // 房屋建筑施工备案
      'i9': '/pages/service/categories/consult/land-planning-consult/index', // 用地规划咨询
      'i10': '/pages/service/categories/subsidy/farmland-protection-subsidy/index', // 耕地地力保护补贴
      'i11': '/pages/service/categories/subsidy/agri-equipment-subsidy/index', // 农机购置补贴
      'i12': '/pages/service/categories/approval/high-standard-farmland-declare/index', // 高标准农田申报
      'i13': '/pages/service/categories/consult/dispute-mediation/index', // 矛盾纠纷调解
      'i14': '/pages/service/categories/other/public-security-report/index', // 治安事件反映
      'i15': '/pages/service/categories/other/key-person-assistance/index', // 重点人员帮扶
      'i16': '/pages/service/categories/consult/medical-enroll-consult/index', // 新农合参保咨询
      'i17': '/pages/service/categories/consult/medical-enroll-consult/index', // 计免接种预约（复用医疗咨询页面）
      'i18': '/pages/service/civil-affairs/apply/index', // 学生资助申请（复用申请页面）
      'i19': '/pages/service/categories/other/hukou-apply/index', // 户籍办理
      'i20': '/pages/service/civil-affairs/apply/index', // 居住证明开具（复用申请页面）
      'i21': '/pages/service/civil-affairs/apply/index', // 婚育证明（复用申请页面）
      'i22': '/pages/service/civil-affairs/apply/index', // 困难证明（复用申请页面）
      'i23': '/pages/service/civil-affairs/apply/index', // 用水报修（复用申请页面）
      'i24': '/pages/service/civil-affairs/apply/index', // 路灯报修（复用申请页面）
      'i25': '/pages/service/civil-affairs/apply/index', // 环境卫生投诉（复用申请页面）
      'i26': '/pages/service/civil-affairs/apply/index', // 秸秆焚烧举报（复用申请页面）
      'i27': '/pages/service/civil-affairs/apply/index', // 河湖巡查上报（复用申请页面）
      'i28': '/pages/service/civil-affairs/apply/index'  // 散养家禽规范指导（复用申请页面）
    }
    
    const targetUrl = serviceMap[id]
    if (targetUrl) {
      wx.navigateTo({ 
        url: targetUrl,
        success: () => console.log('跳转到服务页面成功'),
        fail: (err) => {
          console.error('跳转失败:', err)
          wx.showToast({ title: '页面开发中', icon: 'none' })
        }
      })
    } else {
      wx.showToast({ title: '服务页面不存在', icon: 'none' })
    }
  },

  // 跳转到公告详情
  navigateToNotice(id) {
    if (id) {
      wx.navigateTo({ 
        url: `/pages/village/notice-detail/index?id=${id}`,
        success: () => console.log('跳转到公告详情成功'),
        fail: (err) => {
          console.error('跳转失败:', err)
          wx.showToast({ title: '页面加载失败', icon: 'none' })
        }
      })
    } else {
      wx.showToast({ title: '公告ID不存在', icon: 'none' })
    }
  },

  // 跳转到紧急通知详情
  navigateToUrgent(id) {
    if (id) {
      wx.navigateTo({ 
        url: `/pages/village/notice-detail/index?id=${id}`,
        success: () => console.log('跳转到紧急通知详情成功'),
        fail: (err) => {
          console.error('跳转失败:', err)
          wx.showToast({ title: '页面加载失败', icon: 'none' })
        }
      })
    } else {
      wx.showToast({ title: '通知ID不存在', icon: 'none' })
    }
  },

  // 重新搜索
  onSearchAgain() {
    this.onSearch()
  },

  // 输入框内容变化
  onInputChange(e) {
    this.setData({
      query: e.detail.value
    })
  },

  // 执行搜索
  async onSearch() {
    const query = this.data.query.trim()
    if (!query) {
      wx.showToast({ title: '请输入搜索内容', icon: 'none' })
      return
    }
    
    // 显示加载状态
    this.showGlobalLoading('搜索中...')
    try {
      // 并行调用搜索服务事项和公告的API
      const [serviceResponse, noticeResponse] = await Promise.allSettled([
        this.searchServiceItemsFromAPI(query),
        this.searchNoticesFromAPIOnly(query)
      ])
      
      let allResults = []
      let pagination = null
      let searchInfo = null
      
      // 处理服务事项搜索结果
      if (serviceResponse.status === 'fulfilled' && serviceResponse.value.success) {
        const serviceData = serviceResponse.value.data
        const formattedServices = serviceData.items.map(item => ({
          type: 'service',
          id: item.id,
          title: item.title,
          desc: item.desc,
          dept: item.dept,
          category: item.cateName,
          icon: '',
          online: item.online,
          appoint: item.appoint,
          relevanceScore: item.relevanceScore
        }))
        allResults = [...allResults, ...formattedServices]
        console.log('服务事项搜索结果:', formattedServices.length, '条')
      } else {
        console.error('服务事项搜索失败:', serviceResponse.reason)
      }
      
      // 处理公告搜索结果
      if (noticeResponse.status === 'fulfilled' && noticeResponse.value.success) {
        const noticeData = noticeResponse.value.data
        if (noticeData.notices) {
          const formattedNotices = noticeData.notices.map(notice => ({
            type: 'notice',
            id: notice.id.toString(),
            title: notice.title,
            desc: notice.publishTime ? this.formatNoticeTime(notice.publishTime) : '',
            dept: notice.dept || notice.publisherName,
            typeText: this.getNoticeTypeText(notice.type),
            icon: '',
            readCount: notice.readCount,
            isUrgent: notice.isUrgent,
            publishTime: notice.publishTime,
            publisherName: notice.publisherName
          }))
          allResults = [...allResults, ...formattedNotices]
          pagination = noticeData.pagination
          searchInfo = noticeData.searchInfo
          console.log('公告搜索结果:', formattedNotices.length, '条')
        }
      } else {
        console.error('公告搜索失败:', noticeResponse.reason)
      }
      
      // 如果没有任何搜索结果
      if (allResults.length === 0) {
        wx.showToast({ title: '未找到相关内容', icon: 'none' })
        return
      }
      
      console.log('总搜索结果:', allResults.length, '条')
      
      this.setData({
        results: this.formatSearchResults(allResults),
        pagination: pagination,
        searchInfo: searchInfo
      })
      
      // 搜索完成，隐藏加载状态
      this.hideGlobalLoading()
      
    } catch (error) {
      console.error('搜索API调用失败:', error)
      // 隐藏加载状态
      this.hideGlobalLoading()
      wx.showToast({ 
        title: '网络请求失败，请重试', 
        icon: 'none' 
      })
    }
  },

  // 搜索服务事项API
  async searchServiceItemsFromAPI(keyword) {
    try {
      console.log('调用服务事项搜索API，关键词:', keyword)
      const response = await searchServiceItems(keyword, {
        page: 1,
        limit: 20
      })
      console.log('服务事项搜索API响应:', response)
      return response
    } catch (error) {
      console.error('服务事项搜索API调用失败:', error)
      throw error
    }
  },

  // 搜索公告API（仅公告）
  async searchNoticesFromAPIOnly(keyword) {
    try {
      console.log('调用公告搜索API，关键词:', keyword)
      const response = await searchNotices({
        keyword: keyword,
        page: 1,
        limit: 20,
        sortBy: 'publish_time',
        sortOrder: 'desc'
      })
      console.log('公告搜索API响应:', response)
      return response
    } catch (error) {
      console.error('公告搜索API调用失败:', error)
      throw error
    }
  },

  // 执行搜索逻辑
  performSearch(query) {
    const results = []
    const lowerQuery = query.toLowerCase()
    
    // 服务事项数据源 - 来自服务目录下的各个子页面，包含分类信息
    const services = [
      { id: 'i1', name: '最低生活保障申请', desc: '困难群众最低生活保障资格申请与复核', dept: '民政办', category: '民政社保' },
      { id: 'i2', name: '临时救助', desc: '突发困难家庭临时救助申领', dept: '民政办', category: '民政社保' },
      { id: 'i3', name: '特困供养申请', desc: '分散供养、集中供养对象认定', dept: '民政办', category: '民政社保' },
      { id: 'i4', name: '残疾人两项补贴', desc: '困难残疾人生活补贴、重度护理补贴', dept: '残联联络员', category: '民政社保' },
      { id: 'i5', name: '养老补贴申请', desc: '老年人生活补贴申请办理', dept: '民政办', category: '民政社保' },
      { id: 'i6', name: '宅基地申请', desc: '宅基地资格审核与建设申请', dept: '村两委', category: '城乡建设' },
      { id: 'i7', name: '危房改造申请', desc: '农村危房改造对象认定与补助', dept: '村建专干', category: '城乡建设' },
      { id: 'i8', name: '房屋建筑施工备案', desc: '农房建设施工备案', dept: '村建专干', category: '城乡建设' },
      { id: 'i9', name: '用地规划咨询', desc: '宅基地、生产用地规划政策咨询', dept: '自然资源协管员', category: '城乡建设' },
      { id: 'i10', name: '耕地地力保护补贴', desc: '农户年度耕地保护补贴申领', dept: '农业服务站', category: '农业农村' },
      { id: 'i11', name: '农机购置补贴', desc: '购机补贴申请与资料初审', dept: '农业服务站', category: '农业农村' },
      { id: 'i12', name: '高标准农田申报', desc: '高标准农田建设项目意向申报', dept: '农业服务站', category: '农业农村' },
      { id: 'i13', name: '矛盾纠纷调解', desc: '群众纠纷调解受理与处理进度查询', dept: '综治办', category: '综合治理' },
      { id: 'i14', name: '治安事件反映', desc: '治安隐患/事件上报与流转', dept: '网格员', category: '综合治理' },
      { id: 'i15', name: '重点人员帮扶', desc: '帮扶对象联系与走访预约', dept: '综治办', category: '综合治理' },
      { id: 'i16', name: '新农合参保咨询', desc: '城乡居民医疗参保与变更咨询', dept: '卫健室', category: '教育卫健' },
      { id: 'i17', name: '计免接种预约', desc: '儿童免疫接种预约登记', dept: '卫健室', category: '教育卫健' },
      { id: 'i18', name: '学生资助申请', desc: '困难学生助学金申请', dept: '村教育协理员', category: '教育卫健' },
      { id: 'i19', name: '户籍办理', desc: '户口迁入/迁出申请办理', dept: '派出所', category: '证件办理' },
      { id: 'i20', name: '居住证明开具', desc: '常住人口居住证明出具', dept: '村委办公室', category: '证件办理' },
      { id: 'i21', name: '婚育证明', desc: '婚育情况证明开具', dept: '计生专干', category: '证件办理' },
      { id: 'i22', name: '困难证明', desc: '家庭经济困难证明开具', dept: '民政办', category: '证件办理' },
      { id: 'i23', name: '用水报修', desc: '村内自来水设施故障报修', dept: '水务协管', category: '公共服务' },
      { id: 'i24', name: '路灯报修', desc: '公共照明故障上报与处理', dept: '村建专干', category: '公共服务' },
      { id: 'i25', name: '环境卫生投诉', desc: '垃圾清运、卫生死角反馈', dept: '环卫协管', category: '公共服务' },
      { id: 'i26', name: '秸秆焚烧举报', desc: '发现露天焚烧立即上报', dept: '生态环保员', category: '生态环保' },
      { id: 'i27', name: '河湖巡查上报', desc: '巡河巡湖发现问题上报', dept: '河长办协管', category: '生态环保' },
      { id: 'i28', name: '散养家禽规范指导', desc: '散养家禽管理与整改指导预约', dept: '生态环保员', category: '生态环保' }
    ]
    
    // 获取open页面的公告数据
    const notices = this.getOpenPageData()
    
    // 搜索服务事项
    services.forEach(service => {
      const nameMatch = service.name.toLowerCase().includes(lowerQuery)
      const descMatch = service.desc.toLowerCase().includes(lowerQuery)
      const deptMatch = service.dept.toLowerCase().includes(lowerQuery)
      const categoryMatch = service.category.toLowerCase().includes(lowerQuery)
      
      if (nameMatch || descMatch || deptMatch || categoryMatch) {
        console.log('找到匹配的服务事项:', service.name, '查询:', query)
        results.push({
          type: 'service',
          id: service.id,
          title: service.name,
          desc: service.desc,
          dept: service.dept,
          category: service.category,
          icon: ''
        })
      }
    })
    
    // 搜索公告
    notices.forEach(notice => {
      if (notice.title.toLowerCase().includes(lowerQuery) ||
          notice.dept.toLowerCase().includes(lowerQuery) ||
          notice.typeText.toLowerCase().includes(lowerQuery)) {
        results.push({
          type: 'notice',
          id: notice.id,
          title: notice.title,
          desc: notice.time,
          dept: notice.dept,
          typeText: notice.typeText,
          icon: ''
        })
      }
    })
    
    // 搜索紧急通知 - 添加紧急通知搜索逻辑
    const urgentNotices = [
      { id: 'urgent1', notice: '台风蓝色预警，注意出行安全', time: '10-06', dept: '村委会' },
      { id: 'urgent2', notice: '停电公告：10月8日 08:00-12:00', time: '10-05', dept: '供电所' },
      { id: 'urgent3', notice: '村务公开：9月财务收支情况公示', time: '10-04', dept: '财务室' }
    ]
    
    urgentNotices.forEach(notice => {
      if (notice.notice.toLowerCase().includes(lowerQuery)) {
        results.push({
          type: 'urgent',
          id: notice.id,
          title: notice.notice,
          desc: notice.time,
          dept: notice.dept,
          icon: ''
        })
      }
    })
    
    return results
  },

  // 获取open页面的数据
  getOpenPageData() {
    // 直接返回open页面的items数据
    return [
      { 
        id: 'n1', 
        type: 'notice', 
        typeText: '通知', 
        title: '关于台风预警通知，做好防范准备', 
        time: '10-05', 
        dept: '村委会' 
      },
      { 
        id: 'n2', 
        type: 'notice', 
        typeText: '通知', 
        title: '国庆假期垃圾分类与值班安排', 
        time: '09-28', 
        dept: '村委会' 
      },
      { 
        id: 'f1', 
        type: 'finance', 
        typeText: '财务', 
        title: '2023年9月村财务收支情况公示', 
        time: '10-03', 
        dept: '财务室' 
      },
      { 
        id: 'p1', 
        type: 'project', 
        typeText: '项目', 
        title: '村道路修缮工程进度公示', 
        time: '09-25', 
        dept: '工程部' 
      },
      { 
        id: 'f2', 
        type: 'finance', 
        typeText: '财务', 
        title: '2023年第三季度村集体资产收益公示', 
        time: '10-01', 
        dept: '财务室' 
      },
      { 
        id: 'p2', 
        type: 'project', 
        typeText: '项目', 
        title: '村文化广场建设项目招标公告', 
        time: '09-20', 
        dept: '工程部' 
      }
    ]
  },

  // 格式化搜索结果，支持服务事项和公告两种类型
  formatSearchResults(results) {
    return results.map(item => {
      // 如果已经是格式化后的结果（包含type字段），直接返回
      if (item.type) {
        return item
      }
      
      // 否则按公告格式处理（兼容API返回的数据）
      return {
        type: 'notice',
        id: item.id,
        title: item.title,
        desc: item.contentSummary || item.content,
        dept: item.dept,
        typeText: item.typeText,
        publishTime: item.publishTime,
        readCount: item.readCount,
        isUrgent: item.isUrgent,
        icon: ''
      }
    })
  },

  // 格式化公告结果为搜索结果格式（保留兼容性）
  formatNoticeResults(notices) {
    return notices.map(notice => ({
      type: 'notice',
      id: notice.id,
      title: notice.title,
      desc: notice.contentSummary || notice.content,
      dept: notice.dept,
      typeText: notice.typeText,
      publishTime: notice.publishTime,
      readCount: notice.readCount,
      isUrgent: notice.isUrgent,
      icon: ''
    }))
  },

  // 清空搜索
  onClearSearch() {
    this.setData({
      query: '',
      results: [],
      searchInfo: null,
      pagination: null
    })
  },

  // 测试搜索功能
  testSearch() {
    console.log('测试搜索功能')
    const testQueries = ['最低生活保障', '宅基地', '低保', '补贴', '申请']
    
    testQueries.forEach(query => {
      console.log(`测试查询: ${query}`)
      const results = this.performSearch(query)
      const serviceResults = results.filter(item => item.type === 'service')
      console.log(`查询 "${query}" 找到 ${serviceResults.length} 个服务事项:`, serviceResults.map(r => r.title))
    })
  },

  // 格式化公告时间显示
  formatNoticeTime(timeString) {
    if (!timeString) return ''
    
    try {
      const date = new Date(timeString)
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${month}-${day}`
    } catch (error) {
      console.error('时间格式化失败:', error)
      return ''
    }
  },

  // 获取公告类型的中文显示文本
  getNoticeTypeText(type) {
    const typeMap = {
      'notice': '通知',
      'finance': '财务',
      'project': '项目',
      'policy': '政策',
      'activity': '活动',
      'urgent': '紧急'
    }
    return typeMap[type] || '公告'
  }
})
